//FileUtil.java

package taro.todolist.utils;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;

@Service
public class FileUtil {

    private final String BaseDir = "./files";

    private final String MEMBER = "/member";

    public String uploadFile(MultipartFile file, String text, String type){
        String foldername;
        if ( type.equals("member") )
            foldername = MEMBER;
        else
            throw new IllegalArgumentException(
                "[ERROR]请联系开发人员VincentZyu。 [ERROR_INFO]后端web服务器调用FileUtil 的时候，传入了不合法的type参数"
            );

        Path uploadDir = Paths.get(BaseDir, "/", foldername);
        File folderPath = new File(uploadDir.toUri());

        if (!folderPath.exists())
            folderPath.mkdirs();

        String timestamp = java.time.LocalDate.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd"));
        String FinalFileName = text + "_" + file.getOriginalFilename() + "_" + timestamp;

        Path TargetPath = Paths.get(uploadDir.toString(), FinalFileName);
        System.out.println(
                "[DEBUG]正在调用FileUtil.uploadFile() [DEBUG_INFO]保存在机子中的目标路径是:" + TargetPath.toString()
        );

        try {
            // 复制文件到目标路径，若文件存在则替换
            Files.copy(file.getInputStream(), TargetPath, StandardCopyOption.REPLACE_EXISTING);
            System.out.println(
                    "[SUCCESS]正在调用FileUtil.uploadFile() [SUCCESS_INFO]文件上传成功！保存在机子中的目标路径是:" + TargetPath.toString()
            );
        } catch (IOException e) {
            // 捕获并处理 I/O 异常
            System.err.println(
                    "[ERROR]请联系开发人员VincentZyu。正在调用FileUtil.uploadFile [ERROR_INFO] 在copy文件时发生错误，捕获并抛出IO异常 e.getMessage(): " + e.getMessage()
            );
        } catch (SecurityException e) {
            // 捕获并处理安全异常
            System.err.println(
                    "[ERROR]请联系开发人员VincentZyu。正在调用FileUtil.uploadFile [ERROR_INFO] 在copy文件时发生错误，捕获并抛出安全异常， e.getMessage(): " + e.getMessage()
            );
        }

        return TargetPath.toString();

    }

    public byte[] getImageByteArray(String FileName) {
        byte[] ImageBytes = null;
        try {
            Path FilePath = Paths.get(FileName);
            System.out.println(
                    "[DEBUG]正在调用FileUtil.getImageByteArray() [DEBUG_INFO] 转换成URI的FilePath: " + FilePath.toUri()
            );
//            File file = Paths.get(FilePath.toUri()).toFile();
//            System.out.println(
//                    "[DEBUG]正在调用FileUtil.getImageByteArray() [DEBUG_INFO] 把刚刚的URI转换成File: " + file
//            );
            ImageBytes = Files.readAllBytes(FilePath);
        } catch (InvalidPathException e) {
            // 路径无效
            System.err.println(
                    "[ERROR]请联系开发人员VincentZyu。正在调用FileUtil.getImageByteArray() [ERROR_INFO] 不合法的文件路径， e.getMessage(): " + e.getMessage()
            );
        } catch (IOException e) {
            // IO 异常，无法读取文件
            System.err.println(
                    "[ERROR]请联系开发人员VincentZyu。正在调用FileUtil.getImageByteArray() [ERROR_INFO] 无法读取文件， e.getMessage(): " + e.getMessage()
            );
        } catch (Exception e) {
            // 其他异常
            System.err.println(
                    "[ERROR]请联系开发人员VincentZyu。正在调用FileUtil.getImageByteArray() [ERROR_INFO] 遇到未知异常， e.getMessage(): " + e.getMessage()
            );
        }

        return ImageBytes;
    }

    public void deleteFile(String filePath) {
        try {
            Path pathToDelete = Paths.get(filePath);
            Files.delete(pathToDelete);
            System.out.println("[SUCCESS] 文件删除成功: " + filePath);
        } catch (NoSuchFileException e) {
            System.err.println("[ERROR] 文件不存在: " + filePath);
        } catch (IOException e) {
            System.err.println("[ERROR] 删除文件时发生错误: " + e.getMessage());
        }
    }


}
